package com.example.demo.t2;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class LRUCache<K, V> implements Iterable<K> {

    int MAX = 3;
    LinkedHashMap<K, V> cache = new LinkedHashMap<>();
    public void cache(K key, V value) {
        if (cache.containsKey(key)) {
            cache.remove(key);
        } else if(cache.size() >= MAX) {
            // 去掉最老的
            Iterator<K> keys = cache.keySet().iterator();
            K firstKey = keys.next();
            cache.remove(firstKey);
        }
        cache.put(key, value);
    }


    @Override
    public Iterator<K> iterator() {
        var it = cache.keySet().iterator();
        return new Iterator<K>() {
            @Override
            public boolean hasNext() {
                return it.hasNext();
            }

            @Override
            public K next() {
                return it.next();
            }
        };
    }

    public static void main(String[] args) {

        LRUCache<String, Integer> lru = new LRUCache<>();
        lru.cache("A", 34);
        lru.cache("B", 34);
        lru.cache("C", 34);
        lru.cache("A", 34);
        lru.cache("D", 34);

        System.out.println(
                "Leave <- " +
        StreamSupport.stream(lru.spliterator(), false)
                .map(o -> o.toString())
                .collect(Collectors.joining("<-"))
        );


    }
}
